package cn.yoaket.web;

import cn.yoaket.algorithm.Shadow;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Polygon;
import cn.yoaket.unit.Edge;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ShadowGenerate")
public class ShadowGenerate extends HttpServlet {

    String toCoordinates(List<Polygon> interShadows){
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (Polygon interShadow : interShadows) {
            Coordinate[] coordinates = interShadow.getCoordinates();
            str.append("[[");
            for (Coordinate coordinate : coordinates) {
                str.append("[").append(coordinate.getX()).append(",").append(coordinate.getY()).append("]").append(",");
            }
            str.deleteCharAt(str.length()-1);
            str.append("]],");
        }
        str.deleteCharAt(str.length()-1);
        str.append("]");

        return str.toString();
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context = getServletContext();

        String az = request.getParameter("az");
        String el = request.getParameter("el");
        double azAngle = 90;
        double elAngle = 0;

        List<Edge>    edges =     (List<Edge>)context.getAttribute("edges");
        List<Polygon> buildings = (List<Polygon>)context.getAttribute("buildings");


        System.out.println(buildings.size());


        if(!az.equals("dark") && !el.equals("dark")){
            azAngle = Double.parseDouble(az);
            elAngle = Double.parseDouble(el)-180;
        }

        List<Polygon> shadows = new ArrayList<>();
        for (Polygon building : buildings) {
            shadows.add(Shadow.projection(building, azAngle, elAngle));
        }
        List<Polygon> interShadows = new ArrayList<>();
        for (Edge edge : edges) {
            interShadows.addAll(Shadow.getRatio(edge,shadows));
        }
        response.setContentType("text/json");
        PrintWriter out = response.getWriter();
        out.print(toCoordinates(interShadows));
    }
}
